﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Runtime.InteropServices;

namespace gametest.DxAPI
{
    public class DxTimer
    {
        [DllImport("kernel32")]
        private static extern bool QueryPerformanceFrequency(ref long frequency);
        [DllImport("kernel32")]
        private static extern bool QueryPerformanceCounter(ref long count);

        private long lLastTime = 0;
        private long lCurrentTime = 0;
        private bool bInitialized = false;
        private double dElapsedSeconds = 0.0;
        private double dElapsedMilliseconds = 0.0;
        private bool bTimerStart = true;

        private long lTicksPerSecond = 0;
        public long TicksPerSecond
        {
            get { return lTicksPerSecond; }
        }

        public DxTimer()
        {
            if (!QueryPerformanceFrequency(ref lTicksPerSecond)) throw new Exception("Performance Counter not supported!");
            bInitialized = true;
        }

        public void markTime()
        {
            if (!bInitialized) throw new Exception("Timer not initialized!");
            if (bTimerStart)
            {
                QueryPerformanceCounter(ref lLastTime);
                bTimerStart = false;
            }
        }

        public double msElapsed()
        {
            if (!bInitialized) throw new Exception("Timer not initialized!");
            QueryPerformanceCounter(ref lCurrentTime);
            dElapsedMilliseconds = ((double)(lCurrentTime - lLastTime) / (double)lTicksPerSecond) * 1000.0;
            lLastTime = lCurrentTime;
            return dElapsedMilliseconds;
        }

        public double secElapsed()
        {
            if (!bInitialized) throw new Exception("Timer not initialized!");
            QueryPerformanceCounter(ref lCurrentTime);
            dElapsedSeconds = (double)(lCurrentTime - lLastTime) / (double)lTicksPerSecond;
            lLastTime = lCurrentTime;
            return dElapsedSeconds;
        }

        public void resetTime()
        {
            bTimerStart = true;
        }
    }
}
